package com.nk.iexam.ds;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;

import com.nk.iexam.models.Answer;

public class AnswerDataSource extends AbstractObjectDataSource<Answer>
{
	public static final String TABLE_NAME = "tblAnswer";
	public static final String QUESTION_ID = "QuestionID";
	public static final String CONTENT = "Content";
	public static final String IS_CORRECT = "IsCorrect";
	public static final String COMMENT = "Comment";
	
	public AnswerDataSource() {
		super();
		_tableName = TABLE_NAME;
		_allColumnsName.add(QUESTION_ID);
		_allColumnsName.add(CONTENT);
		_allColumnsName.add(IS_CORRECT);
		_allColumnsName.add(COMMENT);
	}

	@Override
	protected Answer cursorToObject(Cursor cursor_)
	{
		Answer answer = new Answer();
		answer.setId(cursor_.getLong(0));
		answer.setQuestionId(cursor_.getLong(1));
		answer.setContent(cursor_.getString(2));
		answer.setCorect(cursor_.getInt(3) == 1);
		answer.setComment(cursor_.getString(4));
		
		return answer;
	}
	
	public Answer create(final String questionId_, final String content_, final boolean isCorrect_, final String comment_) 
	{
		ContentValues values = new ContentValues();
		values.put(QUESTION_ID, questionId_);
		values.put(CONTENT, content_);
		values.put(IS_CORRECT, isCorrect_);
		values.put(COMMENT, comment_);
		
		long insertId = _database.insert(TABLE_NAME, null, values);
		Cursor cursor = _database.query(TABLE_NAME, getAllTableColumnsName(), ID + " = " + insertId, null, null, null, null);
		cursor.moveToFirst();
		Answer answer = cursorToObject(cursor);
		cursor.close();
		return answer;
	}

	public List<Answer> getAllAnswersForQuestion(final long questionId_)
	{
		List<Answer> dbObjects = new ArrayList<Answer>();
		Cursor cursor = _database.query(TABLE_NAME, getAllTableColumnsName(), "QuestionID = " + questionId_, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Answer dbObject = cursorToObject(cursor);
			dbObjects.add(dbObject);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return dbObjects;
	}
}
